package com.unittec.drainage.provider.log;

import com.alibaba.fastjson.JSON;
import com.unittec.drainage.provider.scope.ThreadLocalScope;
import com.unittec.drainage.provider.utils.ExceptionUtil;
import com.unittec.drainage.sdk.root.domain.GatewayRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author wuxinwei
 */
@Aspect
@Component
public class LogAopAspect {

    private final Logger logger = LoggerFactory.getLogger(LogAopAspect.class);

    @Resource
    private Log log;


    /**
     * 切入点描述 这个是controller和service包的切入点
     */
    @Pointcut("(execution(public * com.unittec.drainage.provider.*.controller..*.*(..))  ||  execution(public * com.unittec.drainage.provider.*.service..*.*(..)) ) && !execution(public * com.unittec.drainage.provider.*.controller.LogController.*(..))  && !execution(public * com.unittec.drainage.provider.*.service.LogService.*(..))  &&!execution(* upload*(..))  &&!execution(* export*(..))")
    public void pointCut() {
    }

    /**
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(pointcut = "pointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
        StringBuilder sbLog = new StringBuilder();
        try {
            String s = JSON.toJSONString(joinPoint.getArgs());
            GatewayRequest gatewayRequest = JSON.parseObject(s, GatewayRequest.class);
            log.error(gatewayRequest, joinPoint.getSignature().getName() + "{}  ", "error-----" + e);

            sbLog.append(String.format("【用户】%s", ThreadLocalScope.getAuthData().getUser()));
            sbLog.append(String.format("【类名】%s", joinPoint.getTarget().getClass().getName()));
            sbLog.append(String.format("【方法】%s", joinPoint.getSignature().getName()));
            sbLog.append(String.format("【参数】%s", JSON.toJSONString(gatewayRequest)));
            sbLog.append(String.format("【错误】%s", ExceptionUtil.getExceptionMessage(e)));
        } catch (Exception ex) {
            try {
                String method = joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName();
                log.sysAopMethodLog(method, ThreadLocalScope.getAuthData().getRequestId(),"【错误信息】" + ExceptionUtil.getExceptionMessage(e));
            } catch (Exception ex2) {
                logger.error("【" + ThreadLocalScope.getAuthData().getRequestId() + "】" + "LogAopAspect doAfterThrowing error", e);
            }
        }
    }


    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        return printLog(joinPoint);
    }


    /**
     * 打印日志
     *
     * @param joinPoint
     * @return
     */
    private Object printLog(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = null;
        StringBuilder sbLog = new StringBuilder();
        sbLog.append(String.format("【用户】%s", ThreadLocalScope.getAuthData().getUser()));
        sbLog.append(String.format("【类名】%s", joinPoint.getTarget().getClass().getName()));

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        sbLog.append(String.format("【方法】%s", methodSignature.getMethod().getName()));

        Object[] args = joinPoint.getArgs();
        for (Object o : args) {
            sbLog.append(String.format("【参数】%s", JSON.toJSONString(o)));
        }

        long startTime = System.currentTimeMillis();
        result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        sbLog.append(String.format("【返回】%s", JSON.toJSON(result)));
        sbLog.append(String.format("【耗时】%s ms", endTime - startTime));
        try {
            log.sysAopMethodLog(joinPoint.getSignature().getName(),ThreadLocalScope.getAuthData().getRequestId(), sbLog.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error("【" + ThreadLocalScope.getAuthData().getRequestId() + "】" + "LogAopAspect printLog error", ex);
        }
        return result;
    }
}
